package com.bafa.dbcache;

import java.sql.ResultSet;
import java.util.Calendar;
import java.util.TreeSet;

import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.objects.season.Division;
//import com.bafa.objects.Score;
//import com.bafa.objects.Scorer;
import com.bafa.objects.season.Season;
import com.bafa.objects.schema.*;
import com.bafa.objects.TeamAward;
//import com.bafa.objects.TeamSeason;
//import com.bafa.objects.TeamStats;
import com.bafa.services.RetrieveServices;
import com.bafa.util.comparators.TopScorerComparator;

public class GrabTeamSeason {

	
	public static void grabTeamSeason(DBAccess db, int seasonId, int teamId, TeamStats stats)throws Exception{
		ObjectFactory factory=new ObjectFactory();
		TeamSeason teamSeason = factory.createTeamSeason();
		teamSeason.setSeasonId(seasonId);
		//		********************Grab Scorers***********************
		grabGoalScorers(db,seasonId,teamId,teamSeason,stats);
		//*******************************************************
		
		//***********Grab cleansheets************
		grabCleanSheets(db,seasonId,teamId,teamSeason, stats);
		//**********************End of Grab*******************
			
		//*******************Grab goals scored****************
		grabGoals(db,seasonId,teamId,teamSeason,stats);
		//*********************End grab***********************
				
		//*******************Grab goals conceded****************
		grabGoalsConceded(db,seasonId,teamId,teamSeason,stats);
		//*********************End grab***********************
		
		//********************Grab results*********************
		grabGamesResults(db,seasonId,teamId,teamSeason,stats);
		//*****************************************************
		
		//********************Grab positions*********************
		//grabLeaguePosition(db,seasonId,teamId,teamSeason,stats);
		//*****************************************************
		
		//********************Grab matches*********************
		grabMatches(db,seasonId,teamId,teamSeason,stats);
		//*****************************************************
		
		
		stats.getTeamSeason().add(teamSeason);
	}
	
	private static void grabCleanSheets(DBAccess db,int seasonId, int teamId,TeamSeason teamSeason, TeamStats stats)throws Exception{
		ObjectFactory factory=new ObjectFactory();
		Record record = factory.createRecord();
		//First is as TEAMA
		QueryObject matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("seasonID",""+seasonId);
		matchesQuery.addWhereAndField("teamA",""+teamId);
		matchesQuery.addWhereAndField("goalsB","0");
		ResultSet matchesResult = db.count(matchesQuery);
		int amount = 0;
		while(matchesResult.next()){
			amount=amount+matchesResult.getInt(1);
		}
		
		//Now as TEAMB
		matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("seasonID",""+seasonId);
		matchesQuery.addWhereAndField("teamB",""+teamId);
		matchesQuery.addWhereAndField("goalsA","0");
		matchesResult = db.count(matchesQuery);
		while(matchesResult.next()){
			amount=amount+matchesResult.getInt(1);
		}
		
		//set record amount of cleansheets
		if(stats.getRecordCleanSheets()==null || amount > stats.getRecordCleanSheets().getNumber()){
			record.setNumber(amount);
			record.setSeasonId(seasonId);
			stats.setRecordCleanSheets(record);
		}
		
		//set on team season
		if(teamSeason!=null)teamSeason.setNumberOfCleanSheets(amount);
		
		
	}
	
	private static void grabGoals(DBAccess db,int seasonId,int teamId,TeamSeason teamSeason, TeamStats stats)throws Exception{
		ObjectFactory factory=new ObjectFactory();
		Record record = factory.createRecord();
		//		First is as TEAMA
		QueryObject matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("seasonID",""+seasonId);
		matchesQuery.addWhereAndField("teamA",""+teamId);
		ResultSet matchesResult = db.query(matchesQuery);
		int amount = 0;
		int KOamount = 0;
		while(matchesResult.next()){
			boolean knockout = !(matchesResult.getInt("Division")>=1);
			if(knockout){
				KOamount=KOamount+matchesResult.getInt("GoalsA");
			}else{
				amount=amount+matchesResult.getInt("GoalsA");
			}
		}
		
		//Now as TEAMB
		matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("seasonID",""+seasonId);
		matchesQuery.addWhereAndField("teamB",""+teamId);
		matchesResult = db.query(matchesQuery);
		while(matchesResult.next()){
			boolean knockout = !(matchesResult.getInt("Division")>=1);
			if(knockout){
				KOamount=KOamount+matchesResult.getInt("GoalsB");
			}else{
				amount=amount+matchesResult.getInt("GoalsB");
			}
		}
		//set record amount of cleansheets
		if(stats.getRecordGoalsScored()==null ||amount+KOamount > stats.getRecordGoalsScored().getNumber()){
			record.setNumber(amount+KOamount);
			record.setSeasonId(seasonId);
			stats.setRecordGoalsScored(record);
		}
		//set season goals scored
		if(teamSeason!=null)teamSeason.setNumberOfLeagueGoalsScored(amount);
		if(teamSeason!=null)teamSeason.setNumberOfSeasonGoalsScored(amount+KOamount);
		
	}
	
	private static void grabGoalsConceded(DBAccess db,int seasonId,int teamId,TeamSeason teamSeason,TeamStats stats)throws Exception{
		ObjectFactory factory=new ObjectFactory();
		Record record = factory.createRecord();
		//		First is as TEAMA
		QueryObject matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("seasonID",""+seasonId);
		matchesQuery.addWhereAndField("teamA",""+teamId);
		ResultSet matchesResult = db.query(matchesQuery);
		int amount = 0;
		int KOamount = 0;
		while(matchesResult.next()){
			boolean knockout = !(matchesResult.getInt("Division")>=1);
			if(knockout){
				KOamount=KOamount+matchesResult.getInt("GoalsB");
			}else{
				amount=amount+matchesResult.getInt("GoalsB");
			}
		}
		
		//Now as TEAMB
		matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("seasonID",""+seasonId);
		matchesQuery.addWhereAndField("teamB",""+teamId);
		matchesResult = db.query(matchesQuery);
		while(matchesResult.next()){
			boolean knockout = !(matchesResult.getInt("Division")>=1);
			if(knockout){
				KOamount=KOamount+matchesResult.getInt("GoalsA");
			}else{
				amount=amount+matchesResult.getInt("GoalsA");
			}
		}
		//set record amount of cleansheets
		if(stats.getRecordGoalsConceded()==null ||amount+KOamount > stats.getRecordGoalsConceded().getNumber()){
			record.setNumber(amount+KOamount);
			record.setSeasonId(seasonId);
			stats.setRecordGoalsConceded(record);
		}
		
		//set season clean sheets
		if(teamSeason!=null)teamSeason.setNumberOfLeagueGoalsConceded(amount);
		if(teamSeason!=null)teamSeason.setNumberOfSeasonGoalsConceded(amount+KOamount);
		
	}
	
	
	private static void grabGamesResults(DBAccess db,int seasonId,int teamId,TeamSeason teamSeason,TeamStats stats)throws Exception{
		ObjectFactory factory=new ObjectFactory();
		Record record = factory.createRecord();
		QueryObject matchesQuery= new QueryObject("matches");
		
		//		First is as TEAMA
		matchesQuery.addWhereAndField("SeasonID",""+seasonId);
		matchesQuery.addWhereAndField("TeamA",""+teamId);
		matchesQuery.addWhereAndField("Played","1");
		ResultSet matchesResult = db.query(matchesQuery);
		int won = 0;
		int lost=0;
		int drawn=0;
		int KOwon=0;
		int KOlost=0;
		int KOdrawn=0;
		int amount = 0;
		int KOamount = 0;
		while(matchesResult.next()){
			boolean knockout = !(matchesResult.getInt("Division")>=1);
			if(knockout){
				KOamount++;
				if(matchesResult.getInt("GoalsA")>matchesResult.getInt("GoalsB"))
					KOwon++;
				else if(matchesResult.getInt("GoalsB")>matchesResult.getInt("GoalsA"))
					KOlost++;
				else
					KOdrawn++;
			}
			else{
				amount++;
				if(matchesResult.getInt("GoalsA")>matchesResult.getInt("GoalsB"))
					won++;
				else if(matchesResult.getInt("GoalsB")>matchesResult.getInt("GoalsA"))
					lost++;
				else
					drawn++;
			}
		}
		
		//Now as TEAMB
		matchesQuery= new QueryObject("matches");
		matchesQuery.addWhereAndField("SeasonID",""+seasonId);
		matchesQuery.addWhereAndField("TeamB",""+teamId);
		matchesQuery.addWhereAndField("Played","1");
		matchesResult = db.query(matchesQuery);
		int points = 0;
		while(matchesResult.next()){
			boolean knockout = !(matchesResult.getInt("Division")>=1);
			if(knockout){
				KOamount++;
				if(matchesResult.getInt("GoalsB")>matchesResult.getInt("GoalsA"))
					KOwon++;
				else if(matchesResult.getInt("GoalsA")>matchesResult.getInt("GoalsB"))
					KOlost++;
				else
					KOdrawn++;
			}
			else{
				amount++;
				if(matchesResult.getInt("GoalsB")>matchesResult.getInt("GoalsA"))
					won++;
				else if(matchesResult.getInt("GoalsA")>matchesResult.getInt("GoalsB"))
					lost++;
				else
					drawn++;
			}
		}
		
		if(teamSeason!=null)teamSeason.setNumberOfLeagueGamesWon(won);
		if(teamSeason!=null)teamSeason.setNumberOfLeagueGamesLost(lost);
		if(teamSeason!=null)teamSeason.setNumberOfLeagueGamesDrawn(drawn);
		if(teamSeason!=null)teamSeason.setNumberOfSeasonGamesWon(won+KOwon);
		if(teamSeason!=null)teamSeason.setNumberOfSeasonGamesLost(lost+KOlost);
		if(teamSeason!=null)teamSeason.setNumberOfSeasonGamesDrawn(drawn+KOdrawn);
		if(teamSeason!=null)teamSeason.setNumberOfLeagueGamesPlayed(amount);
		if(teamSeason!=null)teamSeason.setNumberOfSeasonGamesPlayed(amount+KOamount);
		
		points = won*3;
		points = points+(drawn*1);
		if(teamSeason!=null)teamSeason.setPoints(points);
		
	}
	
	private static void grabGoalScorers(DBAccess db,int seasonId,int teamId,TeamSeason teamSeason,TeamStats stats)throws Exception{
		ObjectFactory factory = new ObjectFactory();
		
		QueryObject scorersQuery = new QueryObject("scorers");
		StringBuffer buffer = new StringBuffer();
		buffer.append("select distinct scorername, sum(numberofgoals) totalgoals from scorers where teamid=");
		buffer.append(teamId);
		buffer.append(" and seasonId=");
		buffer.append(seasonId);
		buffer.append(" group by scorername order by totalgoals desc");
		scorersQuery.setQueryString(buffer.toString());
		ResultSet scorersResult = db.query(scorersQuery);
		while(scorersResult.next()){
			Scorer scorer = factory.createScorer();
			String name = scorersResult.getString(1);
			int goals = scorersResult.getBigDecimal("totalgoals").intValue();
			scorer.setGoals(goals);
			scorer.setName(name);
			scorer.setTeamId(teamId);
			scorer.setSeasonId(seasonId);
			if(teamSeason!=null)teamSeason.getScorer().add(scorer);
			//set record goals scored in a season
			if(stats.getRecordGoalScorer()==null || goals > stats.getRecordGoalScorer().getGoals())stats.setRecordGoalScorer(scorer);
		}
	}
	
	private static void grabMatches(DBAccess db, int seasonId, int teamId, TeamSeason teamSeason, TeamStats stats)throws Exception{
		String query = "select * from matches where SeasonId="+seasonId+" and (TeamA="+teamId+" or TeamB="+teamId+") order by Date asc, Time asc";
		ObjectFactory factory = new ObjectFactory();
		
		
		QueryObject matchesQuery = new QueryObject("matches");
		matchesQuery.setQueryString(query);
		ResultSet matchesResult = db.query(matchesQuery);
		
		while(matchesResult.next()){
			Score score = factory.createScore();
			Calendar cal = Calendar.getInstance();
			if(matchesResult.getDate("Date")!=null)cal.set(matchesResult.getDate("Date").getYear()+1900,matchesResult.getDate("Date").getMonth(),matchesResult.getDate("Date").getDate());
			int oppo = 0;
			int goalsFor = 0;
			int goalsAgainst = 0;
			int oppoAdded = 0;
			int weAdded = 0;
			boolean home = false;
			if(matchesResult.getInt("TeamB")==teamId){
				
				home = false;
			}else if(matchesResult.getInt("TeamA")==teamId){
				
				home=true;
			}
			score.setHome(home);
			score.setID(matchesResult.getInt("ID"));
			
			//grabScorersForScore(score,teamId,db);
			if(teamSeason!=null)teamSeason.getMatch().add(score);
			
		}
	}
	/*
	private static void grabLeaguePosition(DBAccess db,int seasonId,int teamId,TeamSeason teamSeason,TeamStats stats)throws Exception{
		Season season = DisplayServices.getSeason(seasonId+"");
		if(season.isSwitchedOn()){
			Division[] divisions = season.divisionArray();
		
		for(int i=0;i<divisions.length;i++){
			
			Division division = divisions[i];
			
			int[] teams = division.teamIdArray();
			for(int j=0;j<teams.length;j++){
				int thisTeamId = teams[j];
				if(thisTeamId==teamId){
					if(teamSeason!=null)teamSeason.setDivision(division.getDivision());
					int pos = j+1;
					if(teamSeason!=null)teamSeason.setPosition(pos);
					if(season.isCompleted()){
						TeamAward award = new TeamAward();
						boolean add = false;
						if(pos==1){
							award.setChampion(true);
							add = true;
						}
						else if(pos==2){
							award.setRunnerup(true);
							add=true;
						}
						if(add){
							award.setSeasonId(seasonId);
							award.setDivision(division.getDivision());
							//stats.addAwards(seasonId,award);
						}
						
					}
				}
			}
		}
		}
	}*/
}
